<?php

namespace forfun\service;

use forfun\constant\ErrorCode;
use forfun\context\CoreContext;
use forfun\exception\ForFunException;
use forfun\repository\AgreeRecordRepository;
use forfun\repository\CommentRepository;
use forfun\repository\entity\AgreeRecord;
use restphp\biz\PageParam;

class CommentService {
    /**
     * 获取评论列表.
     * @param $kind
     * @param $bizId
     * @param $page
     * @return array
     */
    public static function getCommentList($kind, $bizId, $page) {
        $commentRepository = new CommentRepository();
        $arrData = $commentRepository->select(array(
            'rule' => array(
                'kind' => $kind,
                'biz_id' => $bizId
            ),
            'page_param' => PageParam::getInstance($page, APP_DATA_LIST_PAGE_SIZE),
            'order' => 'order by id desc'
        ), false);
        $arrUserIds = array();
        foreach ($arrData as $arrItem) {
            $arrUserIds[] = $arrItem['user_id'];
        }

        $userNameMap = UserService::getUsernameMapByIds($arrUserIds);
        foreach ($arrData as &$arrItem) {
            $arrItem['username'] = $userNameMap[$arrItem['user_id']];
        }
        return $arrData;
    }
    /**
     * 添加评论.
     * @param $kind
     * @param $bizId
     * @param $comment
     * @return void
     */
    public static function addComment($kind, $bizId, $comment) {
        $commentRepository = new CommentRepository();
        $todayMax = $commentRepository->countCommentToday(CoreContext::getUser()->getId(), $kind, $bizId);
        if ($todayMax >= APP_COUPLET_MAX_REPLY_OF_ONE) {
            throw new ForFunException(ErrorCode::COMMENT_OVER_MAX_OF_ONE);
        }

        $commentRepository->addComment(CoreContext::getUser()->getId(), $kind, $bizId, $comment);
    }

    /**
     * 点赞.
     * @param $id
     * @return void
     * @throws ForFunException
     * @throws \ReflectionException
     */
    public static function addFavour($id) {
        $commentRepository = new CommentRepository();
        $comment = $commentRepository->findOneById($id);
        if (null == $comment) {
            throw new ForFunException(ErrorCode::COMMENT_NOT_EXIST);
        }
        $agreeRepository = new AgreeRecordRepository();
        $agreeRecord = $agreeRepository->getAgreeRecord(CoreContext::getUser()->getId(), AgreeRecord::TYPE_COMMENT, $id);
        if (null != $agreeRecord) {
            throw new ForFunException(ErrorCode::COMMON_HAD_AGREE);
        }
        $agreeRepository->pUpdateDB()->startTran();
        $agreeRepository->addFavour(CoreContext::getUser()->getId(), AgreeRecord::TYPE_COMMENT, $id);
        $comment->setFavourNumber($comment->getFavourNumber() + 1);
        $commentRepository->save($comment);
        $agreeRepository->pUpdateDB()->commitTran();
    }
}